import {Component, OnInit} from '@angular/core';
import * as moment from 'moment';
import {LocalStorageService} from '../../../lib/service/local-storage.service';
import {StoreProductService} from '../store-product.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {AliyunOssOutputUrl} from 'config/api';
import {adSystemApiUrl} from '../../../../config/api';
import {HttpService} from '../../../lib/service/http.service';
import {TempManageService} from '../../../main/store-product/temp-manage/temp-manage-service';


@Component({
  selector: 'app-order',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss'],
  providers: [StoreProductService, TempManageService]
})
export class ListComponent implements OnInit {

  sliderWidth = 180;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  isCollapsed = false;
  stage = 0;
  searchOpen = false;
  _startDate = null;
  _endDate = null;
  startDate = null;
  endDate = null;
  order_no: string;
  goods_name: string;
  phone;
  nick_name: string;
  order_time = [null, null];
  progress_width = 50;
  jobList = [];
  keyword;
  _createdDate = null;
  wx_id = null;
  title = '';

  _allChecked = false;
  _indeterminate = false;
  sortMap = {};
  loading = false;
  checkedIds = [];
  total:number;
  page = 1;
  pageSize = 7;
  templateList = [];

  message: string;
  isDelete = false;
  refundModalVisible = false; // 退款弹窗
  refund_info;
  refund_remark;
  openGrounding;

  _createdValueChange = () => {

  }

  _disabledCreatedDate = () => {

  }

  _startValueChange = () => {
    if (this._startDate > this._endDate) {
      this._endDate = null;
    }
  }
  _endValueChange = () => {
    if (this._startDate > this._endDate) {
      this._startDate = null;
    }
  }
  _disabledStartDate = (startValue) => {
    if (!startValue || !this._endDate) {
      return false;
    }
    return startValue.getTime() >= this._endDate.getTime();
  }
  _disabledEndDate = (endValue) => {
    if (!endValue || !this._startDate) {
      return false;
    }
    return endValue.getTime() <= this._startDate.getTime();
  }

  toggleCollapsed(value) {
    this.isCollapsed = value;
  }

  constructor(private StoreProductService: StoreProductService,
              private localStorageService: LocalStorageService,
              private _message: NzMessageService,
              private confirmServ: NzModalService,
              private httpService: HttpService,
              private tempManageService: TempManageService
  ) {
  }

  ngOnInit() {
    // this.getOrderList();
    this.getOwnerTemplateList();
    this.getJobList();

  }

  // 获取已添加的消息模板列表
  getJobList() {
    this.loading = true;
    this.tempManageService.getJobList(this.page, this.pageSize,this.stage, JSON.stringify(this.keyword)).subscribe(
      res => {
        this.total = res.data.total;
        this.jobList = res.data.data;
        this.loading = false;
        let nowTime =(new Date()).valueOf();

        if (!!this.jobList) {
          this.jobList.every((val, idx, array) => {
            // console.log('-val-',val);
            if(Date.parse(val.created_at)<nowTime){
              val.state='已发送';
            }
            const page = JSON.parse(val.job_content).page;
            if (page.indexOf('index') !== -1) {
              val.pageType = '首页';
            }
            if (page.indexOf('pages/product/product?id=') !== -1) {
              val.pageType = '商品详情';
            }
            if (page.indexOf('product-list') !== -1) {
              val.pageType = '商品列表';
            }
            if (page.indexOf('pages/group-product/group-product?id=') !== -1) {
              val.pageType = '拼团详情';
            }
            if (page.indexOf('pages/group-buy-list/group-buy-list?tab=') !== -1) {
              val.pageType = '拼团列表';
            }
            if (page.indexOf('pages/index/index?card_coupons_uuid=') !== -1) {
              val.pageType = '卡券';
            }
            return true;
          });
        }
      }
    );
  }
  showCancelConfirm = (id) => {
    const this_ = this;
    this.confirmServ.confirm({
      title: '温馨提示',
      content: '您确定要取消发送吗!',
      showConfirmLoading: true,
      onOk() {
        return new Promise((resolve) => {
          this_.delMsgTemp(id);
          setTimeout(resolve, 1000);
        });
      },
      onCancel() {
      }
    });
  };
  showAgainConfirm = (id) => {
    const this_ = this;
    this.confirmServ.confirm({
      title: '温馨提示',
      content: '您确定要重新发送吗!',
      showConfirmLoading: true,
      onOk() {
        return new Promise((resolve) => {
          this_.delMsgTemp(id);
          setTimeout(resolve, 1000);
        });
      },
      onCancel() {
      }
    });
  };

  showDeleteConfirm = (id) => {
    const this_ = this;
    this.confirmServ.confirm({
      title: '温馨提示',
      content: '您确认要删除吗!',
      showConfirmLoading: true,
      onOk() {
        return new Promise((resolve) => {
          this_.delMsgTemp(id);
          setTimeout(resolve, 1000);
        });
      },
      onCancel() {
      }
    });
  }

  handleCancel() {
    this.isDelete = false;
  }


  /*
  *
  * https://api.usexcx.cn/v1/member/wechat/del_message_template?template_id=csTsjOThH5y5H-hkAiIbvYltFyKk9l4q5ETnpuaciMk&applet_uuid=a7dac4d0-913c-11e7-b296-00163e0ca3cb*/
  //删除消息
  delMsgTemp(id) {
    // const url = `${adSystemApiUrl}/v1/member/wechat/del_message_template?template_id=${id}`
    const url = ``;
    return this.httpService.httpPostAuth(url, '').subscribe(
      res => {
        if (res.code === 2000) {
          this._message.create('success','删除成功');
          this.getOwnerTemplateList();
        } else {
          this._message.create('error',res.message);
        }
      }
    );
  }

  // 获取拥有的模板消息列表
  getOwnerTemplateList() {
    const url = `${adSystemApiUrl}/v1/member/wechat/applet_message_template_list?page=1&pageSize=999`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.templateList = res.data.data;
        console.log('-temp-', this.templateList);
        if (!!this.templateList) {
          this.templateList.every((val, idx, array) => {
            if (!!val.extend) {
              val.extend.key_list = JSON.parse(val.extend.key_list);
              val.extend.keyword_list = JSON.parse(val.extend.keyword_list);
              return true;
            } else {
              return false;
            }
          });
        }
      }
    );
  }


  search() {
    if (!this.searchOpen) {
      this.startDate = '';
      this.endDate = '';
    } else {
      this.startDate = this._startDate ? moment(this._startDate).format('YYYY-MM-DD') : '';
      this.endDate = this._endDate ? moment(this._endDate).format('YYYY-MM-DD') : '';
    }

    this.keyword = {
      'start_time': this.startDate,
      'end_time': this.endDate,
      'created_at': this._createdDate ?  moment(this._createdDate).format('YYYY-MM-DD') : '',
    };

    if(/^[a-zA-Z]{2}\d{4}$/.test(this.order_no)) {
      this.keyword['wx_id'] = this.order_no;
    } else {
      this.keyword['title'] = this.order_no;
    }

    this.page = 1;
    this.pageSize = 7;
   this.getJobList();
  }

  reset() {
    this.order_no = '';
    this.goods_name = '';
    this.nick_name = '';
    this._startDate = '';
    this._endDate = '';
    this.startDate = '';
    this._createdDate = '';
    this.endDate = '';
    this.phone = '';
    this.keyword = '';
    this.getJobList();
  }

  _refreshStatus(e?, id?) {
    event.stopPropagation();
    if (e) {
      this.checkedIds.push(id);
    } else {
      this.checkedIds.every((val, idx, array) => {
        if (id === val) {
          this.checkedIds.splice(idx, 1);
          return false;
        }
        return true;
      });
    }
    const allChecked = this.jobList.every(value => value.checked === true);
    const allUnChecked = this.jobList.every(value => !value.checked);
    this._allChecked = allChecked;
    this._indeterminate = (!allChecked) && (!allUnChecked);
  };

  _checkAll(value) {
    if (value) {
      this.jobList.every((val, idx, array) => {
        if (!val.checked) {
          val.checked = true;
          this.checkedIds.push(val.id);
        }
        return true;
      });
    } else {
      this.jobList.every((val, idx, array) => {
        if (val.checked) {
          val.checked = false;
          this.checkedIds.every((val1, idx1, array1) => {
            if (val.id === val1) {
              this.checkedIds.splice(idx1, 1);
              return false;
            }
            return true;
          });
        }
        return true;
      });
    }
    this._refreshStatus();
  };

  sort(sortName, value) {
    if (value) {
      console.log(value);
      this.sortMap[sortName] = value.slice(0, -3);
    } else {
      delete this.sortMap[sortName];
    }
    this.getJobList();
  }

  changeJobType(stage) {
    if (stage === this.stage) return;
    this.checkedIds = [];
    this.stage = stage;
    this.page = 1;
    this.getJobList();
  }

  turnParse(str) {
    return JSON.parse(str);
  }
}
